package pv.finder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pv.control.SubCategoryAdapter;
import pv.control.SubCategoryView;
import pv.control.SubCategoryView.onSubCategoryListener;
import pv.dto.DistrictDTO;
import pv.dto.PlaceDTO;
import pv.dto.SubCategoryDTO;
import pv.fbv3.CustomCallback.LoginCallback;
import pv.fbv3.FacebookHelperv3;
import pv.finder.MySetting.MAPMODE;
import pv.finder.Values.TYPEPLACE;
import pv.finder.search.DistrictSearch;
import pv.map.CustomInfoWindows;
import pv.map.MapHelper;
import pv.util.Utility;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;

public class FMMap extends Fragment implements OnCheckedChangeListener,
		DataHelper.LoadDataListener, onSubCategoryListener,
		View.OnClickListener, OnInfoWindowClickListener, LoginCallback {
	// google map
	protected MapHelper mapHelper;
	protected DataHelper dataHelper;
	protected List<PlaceDTO> listPlaces;
	protected Map<Integer, Marker> mapMarker;
	protected int subSelectedID = -1;
	// data
	protected SubCategoryView layoutSubCategory;
	protected SubCategoryAdapter adapSubCategory;
	protected boolean isShowOption = false;
	protected boolean isShowSetting = false;
	TYPEPLACE type;

	// facebook
	FacebookHelperv3 fh = FacebookHelperv3.getInstance();

	public FMMap() {

		mapMarker = new HashMap<Integer, Marker>();

	}

	// public FMMap(DataHelper dataHelper) {
	//
	// this.dataHelper = dataHelper;
	// }

	protected static final int getDrawableATM(int subCategoryID) {

		// final Random random = new Random();
		// int index = random.nextInt(5);
		int index = subCategoryID % 5;
		switch (index) {
		case 0:
			return R.drawable.atm_1;

		case 1:
			return R.drawable.atm_2;
		case 2:

			return R.drawable.atm_3;
		case 3:

			return R.drawable.atm_4;
		case 4:

			return R.drawable.atm_5;

		default:
			return R.drawable.atm_6;
		}

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mapHelper != null) {
			mapHelper.onResume();
			mapHelper.moveToCurrent();

		}
		// for facebook
		if (fh != null) {
			fh.onResume();
		}
		isShowOption = false;
		isShowSetting = false;
		removeSubContent();

	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mapHelper != null)
			mapHelper.onPause();
		if (fh != null) {
			fh.onPause();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		if (mapHelper != null)
			mapHelper.onSaveInstanceState(outState);
		outState.putInt("subSelectedID", subSelectedID);
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		if (mapHelper != null)
			mapHelper.onLowMemory();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mapHelper != null)
			mapHelper.onDestroy();
		if (fh != null) {
			fh.onDestroy();
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mapHelper = new MapHelper(getActivity());
		mapHelper.onCreate(savedInstanceState);
		dataHelper = new DataHelper(getActivity());

		// try {
		// PackageInfo info = getActivity().getPackageManager()
		// .getPackageInfo("pv.finder",
		// PackageManager.GET_SIGNATURES);
		// for (Signature signature : info.signatures) {
		// MessageDigest md = MessageDigest.getInstance("SHA");
		// md.update(signature.toByteArray());
		// Log.d("KeyHash:",
		// Base64.encodeToString(md.digest(), Base64.DEFAULT));
		// }
		// } catch (NameNotFoundException e) {
		//
		// } catch (NoSuchAlgorithmException e) {
		//
		// }
		// for facebook
		fh = FacebookHelperv3.getInstance();
		fh.init(getActivity());
		fh.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fm_main, null);
		mapHelper.setMapView((MapView) view.findViewById(R.id.map));
		mapHelper.onCreate(savedInstanceState);
		// child on view
		((RadioGroup) view.findViewById(R.id.rgATMGAS))
				.setOnCheckedChangeListener(this);

		((ImageButton) view.findViewById(R.id.btnGPS)).setOnClickListener(this);
		((ImageButton) view.findViewById(R.id.btnsetting))
				.setOnClickListener(this);
		((ImageButton) view.findViewById(R.id.btnoption))
				.setOnClickListener(this);

		((ImageButton) view.findViewById(R.id.btnExitFullScreen))
				.setOnClickListener(this);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mapHelper.onActivityCreated(getActivity());
		if (savedInstanceState != null)
			subSelectedID = savedInstanceState.getInt("subSelectedID");

		init();
		((RadioButton) getView().findViewById(
				type == TYPEPLACE.ATM ? R.id.rb_atm : R.id.rb_gas))
				.setChecked(true);
		if (fh != null) {
			fh.setFragment(this);
			fh.setListener(this);
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		default:
			fh.onActivityResult(requestCode, resultCode, data);
			break;
		}

	}

	protected void init() {
		// TODO Auto-generated method stub

		/* for subcategory */
		initSubList();

		/* for data */
		if (dataHelper != null) {

			DistrictSearch search = new DistrictSearch();
			if (listPlaces == null || listPlaces.isEmpty()) {
				DistrictDTO district = new DistrictDTO(6, "1");
				search.setDistrict(district);
				dataHelper.setListener(this);
				dataHelper.loadData(search);
			} else {
				listPlaces = Arrays.asList(dataHelper.getPlaces());
				addMarkerToMap();
			}

			if (type == TYPEPLACE.ATM) {
				// show subcategory
				showSubList();
			}
		} else {
			dataHelper = new DataHelper(getActivity());

		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		switch (checkedId) {
		case R.id.rb_atm:
			showType(Values.TYPEPLACE.ATM);
			break;

		default:
			showType(Values.TYPEPLACE.GAS);
			break;
		}

	}

	@Override
	public void callback(PlaceDTO[] places) {
		// TODO Auto-generated method stub
		if (places != null && places.length > 0) {
			listPlaces = Arrays.asList(places);
			addMarkerToMap();
		}
	}

	protected void addMarkerToMap() {
		addMarkerToMap(listPlaces.toArray(new PlaceDTO[listPlaces.size()]));
	}

	protected void addMarkerToMap(PlaceDTO[] places) {

		try {
			mapHelper.clear();
			mapMarker.clear();
			Marker m;
			boolean isGAS = ((RadioButton) getView().findViewById(R.id.rb_gas))
					.isChecked();
			for (int i = 0; i < places.length; i++) {
				m = mapHelper.addMarker(
						new LatLng(Double.valueOf(places[i].getLatitude()),
								Double.valueOf(places[i].getLongitude())),
						places[i].getName(), "", getMarkerBitmap(places[i]));

				m.setVisible(isGAS
						&& places[i].getCategory_id() == Values
								.getIDType(TYPEPLACE.GAS));
				if (m != null)
					mapMarker.put(i, m);
			}
			mapHelper.getMap().setInfoWindowAdapter(
					new CustomInfoWindows(getActivity()));
			mapHelper.getMap().setOnInfoWindowClickListener(this);
		} catch (Exception e) {
			// TODO: handle exception
			Utility.LogE(this.getClass(), e);

		}

	}

	protected void showType(Values.TYPEPLACE type) {
		if (mapHelper != null) {
			mapHelper.clearRoute();
		}

		try {
			if (type == TYPEPLACE.GAS) {
				showGas();
			} else {
				showATM();

			}
		} catch (Exception e) {
			// TODO: handle exception
			Utility.LogE(this.getClass(), e);

		}
	}

	public void showATM() {

		showATM(subSelectedID);

	}

	public void showATM(int subID) {
		showSubList();
		PlaceDTO dto;
		for (int i = 0; i < listPlaces.size(); i++) {
			dto = listPlaces.get(i);
			mapMarker.get(i).setVisible(
					dto.getCategory_id() == Values.getIDType(TYPEPLACE.ATM)
							&& dto.getSub_category_id() == subID);
		}
	}

	public void showGas() {
		PlaceDTO dto;
		hideSubList();
		for (int i = 0; i < listPlaces.size(); i++) {
			dto = (PlaceDTO) listPlaces.get(i);
			mapMarker.get(i).setVisible(
					Values.getIDType(TYPEPLACE.GAS) == dto.getCategory_id());
		}

	}

	protected Bitmap getMarkerBitmap(PlaceDTO dto) {
		return dto.getCategory_id() == 1 ? BitmapFactory.decodeResource(
				getResources(), R.drawable.gas) : BitmapFactory.decodeResource(
				getResources(), FMMap.getDrawableATM(dto.getSub_category_id()));
	}

	protected void initSubList() {
		adapSubCategory = new SubCategoryAdapter(getActivity());
		layoutSubCategory = new SubCategoryView(getActivity(),
				(HorizontalScrollView) getView().findViewById(
						R.id.svSubcategory));
		layoutSubCategory.setAdapter(adapSubCategory);

		List<SubCategoryDTO> listSub = Arrays.asList(dataHelper
				.getSubcategorys());
		if (adapSubCategory == null || adapSubCategory.getCount() == 0) {

			if (listSub != null) {
				adapSubCategory.setListData(listSub);
			}

		}
		layoutSubCategory.notifyDataSetChanged();
		subSelectedID = adapSubCategory.getSelectedItem().getId();
		layoutSubCategory.setOnSubCategorySelected(this);

	}

	protected void showSubList() {
		getView().findViewById(R.id.svSubcategory).setVisibility(View.VISIBLE);
	}

	protected void hideSubList() {
		getView().findViewById(R.id.svSubcategory).setVisibility(View.GONE);
	}

	public void onBackPress() {
		// new AlertDialog.Builder(getActivity())
		// .setMessage(getString(R.string.app_name))
		// .setPositiveButton(getString(android.R.string.yes),
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// getActivity().finish();
		// }
		// })
		// .setNegativeButton(getString(android.R.string.no),
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		//
		// }
		// }).show();
		if (isShowOption || isShowSetting) {
			removeSubContent();
			isShowOption = false;
			isShowSetting = false;
			return;
		}
		getActivity().finish();
	}

	@Override
	public void onSubCategorySelected(int position) {
		// TODO Auto-generated method stub
		subSelectedID = adapSubCategory.getItem(position).getId();
		showATM();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.btnGPS) {
			if (mapHelper != null) {
				mapHelper.moveToCurrent();
			}
		} else if (v.getId() == R.id.btnoption) {
			showSubContent(R.id.btnoption);

		} else if (v.getId() == R.id.btnsetting) {
			showSubContent(R.id.btnsetting);
		} else if (v.getId() == R.id.btnExitFullScreen) {
			exitFullScreen();
		}

	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		// TODO Auto-generated method stub
		if (mapHelper != null && marker != null) {
			mapHelper.route(String.valueOf(marker.getPosition().latitude) + ","
					+ String.valueOf(marker.getPosition().longitude),
					MapHelper.MODE_DRIVING);
		}

	}

	public void showSubContent(int btn_id) {
		if (btn_id == R.id.btnoption) {
			showOptionMenu();

		} else if (btn_id == R.id.btnsetting) {
			showSettingMenu();
		}
	}

	Fragment setting = new FMSetting();
	Fragment option = new FMOption();

	protected void showOptionMenu() {
		((ImageButton) getView().findViewById(R.id.btnoption))
				.setBackgroundResource(0);
		if (!isShowOption) {
			if (isShowSetting) {
				((ImageButton) getView().findViewById(R.id.btnsetting))
						.setBackgroundColor(getResources().getColor(
								android.R.color.transparent));
			}
			((ImageButton) getView().findViewById(R.id.btnoption))
					.setBackgroundResource(R.drawable.btn_pressed);
			addToSubContent(option);

		} else {

			removeSubContent();
		}
		isShowOption = !isShowOption;
		isShowSetting = false;
	}

	protected void showSettingMenu() {

		if (!isShowSetting) {
			if (isShowOption) {
				((ImageButton) getView().findViewById(R.id.btnoption))
						.setBackgroundResource(0);
			}
			((ImageButton) getView().findViewById(R.id.btnsetting))
					.setBackgroundResource(R.drawable.btn_pressed);
			addToSubContent(setting);

		} else {
			removeSubContent();

		}
		isShowSetting = !isShowSetting;
		isShowOption = false;
	}

	protected void removeSubContent() {
		// TODO Auto-generated method stub

		((FrameLayout) getView().findViewById(R.id.sub_content))
				.setVisibility(View.GONE);

		((ImageButton) getView().findViewById(R.id.btnoption))
				.setBackgroundColor(getResources().getColor(
						android.R.color.transparent));
		((ImageButton) getView().findViewById(R.id.btnsetting))
				.setBackgroundColor(getResources().getColor(
						android.R.color.transparent));
	}

	protected void addToSubContent(Fragment fragment) {

		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();

		fragmentTransaction.replace(R.id.sub_content, fragment);
		fragmentTransaction.commit();
		((FrameLayout) getView().findViewById(R.id.sub_content))
				.setVisibility(View.VISIBLE);
	}

	public void showMapType(MySetting.MAPMODE mapType) {
		int type = GoogleMap.MAP_TYPE_NONE;

		if (mapType == MAPMODE.NORMAL) {
			type = GoogleMap.MAP_TYPE_NORMAL;

		} else if (mapType == MAPMODE.HYBRID) {
			type = GoogleMap.MAP_TYPE_HYBRID;

		} else if (mapType == MAPMODE.SATELLITE) {
			type = GoogleMap.MAP_TYPE_SATELLITE;

		} else if (mapType == MAPMODE.TERRAIN) {
			type = GoogleMap.MAP_TYPE_TERRAIN;

		}
		mapHelper.getMap().setMapType(type);
	}

	public void fullScreen() {
		getView().findViewById(R.id.layHeader).setVisibility(View.GONE);
		getView().findViewById(R.id.btnGPS).setVisibility(View.GONE);
		getView().findViewById(R.id.btnExitFullScreen).setVisibility(
				View.VISIBLE);

	}

	public void exitFullScreen() {
		getView().findViewById(R.id.layHeader).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.btnGPS).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.btnExitFullScreen).setVisibility(View.GONE);

	}

	public void searchByMode(MySetting.SEARCHMODE searchMode) {

	}

	public void syncData() {
		new AlertDialog.Builder(getActivity())
				.setMessage(getString(R.string.msg_sure_for_erase))
				.setPositiveButton(getString(android.R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();

							}
						})
				.setNegativeButton(getString(android.R.string.no),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();

							}
						}).show();

	}

	public void shareAppOnYourFace() {
		if (fh != null) {

			fh.postStatus(
					"App Tim Kiem Cay Xang & ATM",
					"",
					"picture",
					"Toi da dung ung dung Tim Kiem Cay Xanh & ATM cua ProjectViet",
					"", "GAS&ATM");
		}
	}

	public void logOutFace() {
		if (fh != null) {
			fh.logout();
		}
	}

	@Override
	public void call(Object data) {
		// TODO Auto-generated method stub
		shareAppOnYourFace();
	}
}
